# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '2088882340232130': {  # 万和支付 支付宝H5 3.8% 100-300-500-1000-2000-3000-5000   witch
        'API_KEY': 'lVNRPYqaGmostTWWWD0dRBOoJi1pt9uX',
        'gateway': 'https://api.vpnbb.com/pay/gateway',
    },
    '2088884561631313': {  # 万和支付 微信H5 3.8% 100-300-500-1000-2000-3000-5000   witch
        'API_KEY': '6SW2YWwX0lVOTtyLrMLfAigaeVWuvKBx',
        'gateway': 'https://api.vpnbb.com/pay/gateway',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_pub_key(mch_id):
    return APP_CONF[mch_id]['PUB_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def generate_sign(param, key):
    sign = 'mchid=' + param['mchid'] + '&paytype=' + param['paytype'] + '&amount=' \
           + param['amount'] + '&orderid=' + param['orderid'] + '&ordertime=' \
           + param['ordertime'] + '&' + key
    _LOGGER.info("sign string is: %s", sign)
    return _gen_sign(sign)


def generate_notify_sign(param, key):
    sign = 'mchid=' + param['mchid'] + '&paytype=' + param['paytype'] + '&amount=' \
           + param['amount'] + '&ordertime=' + param['ordertime'] + '&orderstatus=' + param[
               'orderstatus'] + '&orderno=' + param['orderno'] + '&mchorderno=' \
           + param['mchorderno'] + '&' + key
    _LOGGER.info("notify sign string is: %s", sign)
    return _gen_sign(sign)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign:
        _LOGGER.info("wanhepay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>document.forms['submit'].submit();</script>"
    return html


# 必填： 10:微信扫码, 11:微信WAP, 12:微信APP, 13:微信公众号, 20:支付宝扫码, 21:支付宝WAP, 22:支付宝APP, 23:支付宝服务窗,
# 30:QQ扫码, 31:QQWAP, 32:QQ公众号, 40:京东扫码, 41:京东WAP, 42:京东JS, 50:银联扫码, 51:银联WAP, 52:银联快捷, 53:银联网关
def _get_pay_type(service):
    if service == 'alipay_h5':
        return '21'
    elif service == 'wechat_h5':
        return '11'
    return '21'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 下单
def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mchid', app_id),
        ('paytype', _get_pay_type(service)),
        ('orderid', str(pay.id)),
        ('amount', str(int(pay_amount * 100))),
        ('ordertime', local_now().strftime('%Y%m%d%H%M%S')),
        ('callbackurl', '{}/pay/api/{}/wanhepay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('notifyurl', '{}/pay/api/{}/wanhepay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('createip', _get_device_ip(info)),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("wanhepay create: %s, order_id is:%s ", json.dumps(parameter_dict),
                 parameter_dict['orderid'])
    if _get_pay_type(service) in ['alipay_h5', 'wechat_h5']:
        html_text = _build_form(parameter_dict, _get_gateway(app_id))
        cache_id = redis_cache.save_html(pay.id, html_text)
        _LOGGER.info('wanhepay url: %s', settings.PAY_CACHE_URL + cache_id)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}
    else:
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
        _LOGGER.info("wanhepay create rsp data: %s %s", response.status_code, response.text)
        return {'charge_info': json.loads(response.text)['Response']['Result']['payinfo']}


# 通知
def check_notify_sign(request, app_id):
    _LOGGER.info("request body is: %s", request.body)
    data = dict(request.POST.iteritems())
    _LOGGER.info("wanhepay notify data: %s", data)
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['mchorderno']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s", data)
        raise ParamError('wanhepay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['orderstatus'])
    trade_no = str(data['orderno'])
    total_fee = float(data['amount']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    # 支付状态 1-成功 0-失败
    if trade_status == '1':
        _LOGGER.info('wanhepay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


# 查询
def query_charge(pay_order, app_id):
    pass
